<!-- components/crop-image.vue -->
<template>
  <view class="crop-container">
    <view class="image-wrapper">
      <image 
        :src="imagePath" 
        mode="widthFix" 
        @load="onImageLoad"
      ></image>
    </view>
    
    <!-- 裁剪框 -->
    <view class="crop-mask" :style="maskStyle"></view>
    
    <view class="action-bar">
      <button @click="cancel">取消</button>
      <button @click="confirm">确认裁剪</button>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    imagePath: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      imageInfo: {},
      maskWidth: 200,
      maskHeight: 200,
      maskLeft: 0,
      maskTop: 0
    }
  },
  computed: {
    maskStyle() {
      return `width: ${this.maskWidth}px; 
              height: ${this.maskHeight}px; 
              left: ${this.maskLeft}px; 
              top: ${this.maskTop}px;`;
    }
  },
  methods: {
    // 获取图片尺寸
    onImageLoad() {
      uni.getImageInfo({
        src: this.imagePath,
        success: (res) => {
          this.imageInfo = res;
          // 初始化裁剪框位置
          this.initMaskPosition();
        }
      });
    },
    
    // 初始化裁剪框
    initMaskPosition() {
      // 根据图片尺寸计算裁剪框初始位置
      this.maskLeft = (this.imageInfo.width - this.maskWidth) / 2;
      this.maskTop = (this.imageInfo.height - this.maskHeight) / 2;
    },
    
    // 确认裁剪
    confirm() {
      // 使用 canvas 实现裁剪
      this.cropImage();
    },
    
    // 调用 canvas 裁剪图片
    cropImage() {
      const ctx = uni.createCanvasContext('cropCanvas', this);
      
      // 绘制图片到 canvas
      ctx.drawImage(
        this.imagePath, 
        this.maskLeft, this.maskTop, 
        this.maskWidth, this.maskHeight,
        0, 0, 
        this.maskWidth, this.maskHeight
      );
      
      ctx.draw(false, () => {
        // 将 canvas 转换为图片
        uni.canvasToTempFilePath({
          canvasId: 'cropCanvas',
          width: this.maskWidth,
          height: this.maskHeight,
          destWidth: this.maskWidth,
          destHeight: this.maskHeight,
          success: (res) => {
            this.$emit('complete', res.tempFilePath);
          },
          fail: (err) => {
            console.error('裁剪失败:', err);
          }
        }, this);
      });
    },
    
    cancel() {
      this.$emit('cancel');
    }
  }
}
</script>

<style>
.crop-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  z-index: 9999;
}

.image-wrapper {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.crop-mask {
  position: absolute;
  border: 2px dashed #fff;
  background-color: rgba(0,0,0,0.5);
  pointer-events: none;
}

.action-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background-color: #f8f8f8;
}

canvas {
  position: fixed;
  top: -1000rpx;
  left: -1000rpx;
  width: 1px;
  height: 1px;
}
</style>
